package com.example.wsappproject.mainpagefragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Px;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.wsappproject.R;
import com.example.wsappproject.Util.HandlerUtil;
import com.example.wsappproject.Util.OkHttpUtil;
import com.example.wsappproject.adapter.ArticleAdapter2;
import com.example.wsappproject.adapter.ProjectBannerAdapter;
import com.example.wsappproject.constant.ApiInterface;
import com.example.wsappproject.practice.ArticleEntity;
import com.example.wsappproject.practice.BannerEntity;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Leo on 2020/9/27.
 */

public class MainPageFragment extends Fragment {
    private static final String TAG = "MainPageFragment";
    //文章列表下拉刷新控件
    private SwipeRefreshLayout srlArticle;
    //文章列表
    private RecyclerView rvArticle;
    private Context mContext;
    private List<ArticleEntity.DataBean.DatasBean> mArticleList = new ArrayList<>();
    private ArticleAdapter2 mArticleAdapter;

    private int mCurrentPage = 0;
    //广告条banner根视图
    private View mBannerView;
    //广告条banner
    private ViewPager vpBanner;
    //广告条某一条目的标题
    private TextView tvBannerTitle;
    //广告条某一条目的位置
    private TextView tvBannerIndicator;


    /**
     * 创建视图View
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.project_fragment_main_page, null, false);
        srlArticle = inflate.findViewById(R.id.sr_article_project_page);
        rvArticle = inflate.findViewById(R.id.rv_article_project_page);
        return inflate;
    }

    /**
     * 初始化数据，例如网络请求等
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initEvent();
    }

    private void initData() {
        mContext = getContext();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        rvArticle.setLayoutManager(linearLayoutManager);

        //创建广告条View视图
        /*
           注意的点：
         * recyclerview中的item视图，创建的过程中，
         * 第二个参数设置为null，会导致条目被压缩
         * 如何解决？
         *
         */
        mBannerView = LayoutInflater.from(mContext)
                .inflate(R.layout.item_banner_adapter, rvArticle, false);
        vpBanner = mBannerView.findViewById(R.id.vp_banner_item_banner_adapter);
        tvBannerTitle = mBannerView.findViewById(R.id.tv_title);
        tvBannerIndicator = mBannerView.findViewById(R.id.tv_indicator);



        //mArticleList是容量为0的列表，不是null
        //mArticleList传null，会导致ArticleAdapter2::getItemCount方法空指针异常
        mArticleAdapter = new ArticleAdapter2(mContext, mArticleList,mBannerView);
        rvArticle.setAdapter(mArticleAdapter);

        requestBanner();
        requestArticle();
    }

    private void initEvent() {
        srlArticle.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            /**
             * 下拉刷新回调方法
             */
            @Override
            public void onRefresh() {
                mCurrentPage = 0;
                requestArticle();
            }
        });
        rvArticle.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager layoutManager = (LinearLayoutManager) rvArticle.getLayoutManager();
                int itemCount = layoutManager.getItemCount();
                //一条都没有，就不要加载更多了
                if (itemCount == 0) {
                    return;
                }
                //找到最后一条条目显示的位置
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                //最后一条显示的位置等于条目数量减1，说明当前显示的就是最后一条
                if (lastVisibleItemPosition == itemCount - 1 &&
                        //newState == RecyclerView.SCROLL_STATE_IDLE说明RecyclerView结束滑动
                        newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mCurrentPage += 1;
                    srlArticle.setRefreshing(true);
                    requestArticle();
                }
            }
        });
        rvArticle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (mScrollCallback != null) {
                            mScrollCallback.onLeaveScreen();
                        }
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 从网络获取文章列表
     * 接口：https://www.wanandroid.com/article/list/0/json
     * 请求方式GET
     */
    private void requestArticle() {
//        OkHttpClient client = new OkHttpClient();
//        Request.Builder builder = new Request.Builder();
//        builder.url(ApiInterface.ARTICLE_URL);
//        Request request = builder.build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                ArticleEntity articleEntity = new Gson().fromJson(result, ArticleEntity.class);
//
////                errorCode等于0，表示这次业务请求成功，DataBean里面会有数据
////                如果不等于0，表示这次业务请求失败（有可能是参数错误之类的问题），DataBean一般为null
////
////                请求成功与否的标识值，不一定为0.需要根据服务端定义来。
//
//                if (articleEntity.getErrorCode() == 0) {
//                    final List<ArticleEntity.DataBean.DatasBean> datas = articleEntity.getData().getDatas();
//                    HandlerUtil.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            mArticleList.addAll(datas);
//                            mArticleAdapter.notifyDataSetChanged();
//                        }
//                    });
//                }
//            }
//        });
        String url = String.format(ApiInterface.ARTICLE_URL, mCurrentPage);
        Log.d(TAG, "requestArticle: " + url);
        OkHttpUtil.enqueue(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                ArticleEntity articleEntity = new Gson().fromJson(result, ArticleEntity.class);
                if (articleEntity.getErrorCode() == 0) {
                    final List<ArticleEntity.DataBean.DatasBean> datas = articleEntity.getData().getDatas();
                    HandlerUtil.post(new Runnable() {
                        @Override
                        public void run() {
                            //请求的是第0页数据，需要将mArticleList列表清空
                            //下拉刷新的业务逻辑：重新加载第0页，其余页码都不要了
                            if (mCurrentPage == 0) {
                                mArticleList.clear();
                            }
                            mArticleList.addAll(datas);
                            mArticleAdapter.notifyDataSetChanged();
                            //下拉条消失
                            srlArticle.setRefreshing(false);                     }
                    });
                }
            }
        });
    }

    /**
     * 从网络拿取广告图数据
     * 接口：https://www.wanandroid.com/banner/json
     * 请求方式GET
     */
    private void requestBanner() {
        OkHttpUtil.enqueue(ApiInterface.BANNER_URL, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String result = response.body().string();
                Log.e(TAG, "onResponse: " + result);
                Gson gson = new Gson();
                final BannerEntity bannerEntity = gson.fromJson(result, BannerEntity.class);
                /*
                errorCode等于0，表示这次业务请求成功，DataBean里面会有数据
                如果不等于0，表示这次业务请求失败（有可能是参数错误之类的问题），DataBean一般为null

                请求成功与否的标识值，不一定为0.需要根据服务端定义来。
                 */
                if (bannerEntity.getErrorCode() == 0) {
                    Log.e(TAG, "onResponse: " + 0);
                    HandlerUtil.post(new Runnable() {
                        @Override
                        public void run() {
                            final List<BannerEntity.DataBean> dataList = bannerEntity.getData();
                            ProjectBannerAdapter bannerAdapter = new ProjectBannerAdapter(dataList, getContext());
                            vpBanner.setAdapter(bannerAdapter);

                            vpBanner.setCurrentItem(dataList.size() * 100000);

                            //初始化banner标题和指示器
                            tvBannerTitle.setText(dataList.get(0).getTitle());
                            tvBannerIndicator.setText("1/" + dataList.size());

                            vpBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int i, float v, @Px int i1) {

                                }

                                /**
                                 * 选中了哪个页面
                                 * @param i 选中页面的位置
                                 */
                                @Override
                                public void onPageSelected(int i) {
                                    tvBannerTitle.setText(dataList.get(i%dataList.size()).getTitle());
                                    tvBannerIndicator.setText(i%dataList.size() + 1 + "/" + dataList.size());
                                }

                                @Override
                                public void onPageScrollStateChanged(int i) {

                                }
                            });


                            showBannerData(bannerEntity.getData());

                        }
                    });
                }
            }


        });
    }
//    private Banner mBanner;
    //轮播图标题列表
    private List<String> mBannerTitleList;
    //轮播图跳转url的列表
    private List<String> mBannerUrlList;
//
      public void showBannerData(List<BannerEntity.DataBean> bannerDataList) {
         mBannerTitleList = new ArrayList<>();
         List<String> bannerImageList = new ArrayList<>();
         mBannerUrlList = new ArrayList<>();
         for (BannerEntity.DataBean bannerData : bannerDataList) {
             mBannerTitleList.add(bannerData.getTitle());
              bannerImageList.add(bannerData.getImagePath());
              mBannerUrlList.add(bannerData.getUrl());
        }
//        //设置banner样式
//        mBanner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
//        //设置图片加载器
//        mBanner.setImageLoader(new GlideImageLoader());
//        //设置图片集合
//        mBanner.setImages(bannerImageList);
//        //设置banner动画效果
//        mBanner.setBannerAnimation(Transformer.DepthPage);
//        //设置标题集合（当banner样式有显示title时）
//        mBanner.setBannerTitles(mBannerTitleList);
//        //设置自动轮播，默认为true
//        mBanner.isAutoPlay(true);
//        //设置轮播时间
//        mBanner.setDelayTime(2000);
//        //设置指示器位置（当banner模式中有指示器时）
//        mBanner.setIndicatorGravity(BannerConfig.CENTER);
//
//        mBanner.setOnBannerListener(new OnBannerListener() {
//            @Override
//            public void OnBannerClick(int position) {
//                String format = String.format("标题：%s 跳转的url：%s",
//                        mBannerTitleList.get(position),
//                        mBannerUrlList.get(position));
//                ToastUtil.showToast(getContext(), format);
//            }
//        });
//        //banner设置方法全部调用完毕时最后调用
//        mBanner.start();
//    }
//    @Override
//    public void onResume() {
//        super.onResume();
//        if (mBanner != null) {
//            mBanner.startAutoPlay();
//        }
//    }
//
//    @Override
//    public void onStop() {
//        super.onStop();
//        if (mBanner != null) {
//            mBanner.stopAutoPlay();
//        }
    }


    /**
     * 滚动到顶部
     */
    public void scrollToTop(){
        rvArticle.scrollToPosition(0);
    }

    private ScrollCallBack mScrollCallback;
    public void setScrollCallback(ScrollCallBack scrollCallback) {
        this.mScrollCallback = scrollCallback;
    }


    public interface ScrollCallBack {
        void onScrolled(RecyclerView recyclerView, int dx, int dy);
        void onLeaveScreen();
    }
}
